package com.plantplaces.ui;

import java.io.File;

import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.fs131046plantplaces.R;

/**
 * Match plants with GPS locations.
 * 
 * @author jonesb
 *
 */
public class LocationFinder extends PlantPlacesActivity  implements LocationListener {
    private static final int MILLISECONDS_PER_SECOND = 1000;
	private static final int CAMERA_REQUEST = 2;
	private TextView txtLatitudeValue;
	private TextView txtLongitudeValue;
	private EditText edtDescription;
	private Button btnSaveSpecimen;
	private Button btnFindSpecimen;
	private LocationManager locationManager;
	private double latitude;
	private double longitude;
	private int refreshInterval;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.location);
        
        txtLatitudeValue = (TextView) findViewById(R.id.txtLatitudeValue);
        txtLongitudeValue = (TextView) findViewById(R.id.txtLongitudeValue);
        edtDescription = (EditText) findViewById(R.id.edtDescription);
        btnSaveSpecimen = (Button) findViewById(R.id.btnSaveLocation);
        btnFindSpecimen = (Button) findViewById(R.id.btnFindSpecimen);
        
        // get access to the location manager.
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        
    }
    
        
    /**
     * This method is invoked when the find Specimen button is clicked, because
     * we set onSearchClicked as the value of the OnClick attribute of the
     * Find Specimen Button.
     * @param v
     */
    public void onSearchClicked(View v) {
    	// create an intent that tells us to go to the Advanced Search Activity.
    	Intent searchIntent = new Intent(this, AdvancedSearchActivity.class);
    	
    	// start that activity.
    	startActivity(searchIntent);
    
    }
    
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
    	
    	// get preferences.
    	SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    	
    	// get the value for the preference which is mapped to keyGPSInterval
    	String strGPSInterval = sharedPreferences.getString(getString(R.string.keyGPSInterval), "60");
    	
    	try {
	    	// convert the string to a number.
	    	refreshInterval = Integer.parseInt(strGPSInterval);
    	} catch (NumberFormatException e) {
    		refreshInterval = 60;
    	}
	    	
    	// request locations.
    	if (locationManager != null) {
	        
			locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, refreshInterval * MILLISECONDS_PER_SECOND, 0, this);
    	}
    	
    	
    	
    }
    
    @Override
    protected void onPause() {
    	// TODO Auto-generated method stub
    	super.onPause();
    	
    	if (locationManager != null) {
    		locationManager.removeUpdates(this);
    	}
    	
    }

    /**
     * Save the specimen to the persistence layer.
     */
    private void save() {
    	String strLat = txtLatitudeValue.getText().toString();
    	String strLng = txtLongitudeValue.getText().toString();
    	String strDescription = edtDescription.getText().toString();
    	
    	// showing a message box confirming the operation is complete.
    	Toast.makeText(this, "Specimen Saved: " + strDescription, Toast.LENGTH_LONG).show();
    }


    /**
     * This method will be invoked when the location changes.
     */
	@Override
	public void onLocationChanged(Location loc) {
		// get the updated location.
		latitude = loc.getLatitude();
		longitude = loc.getLongitude();
		
		// update the user interface.
		txtLongitudeValue.setText("" + longitude);
		txtLatitudeValue.setText("" + latitude);
	}


	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == CAMERA_REQUEST) {
				// we don't need to do anything, since the camera is saving the image on the file system, but let's go ahead and put up a success message anyway.
				Toast.makeText(this, getString(R.string.picture_saved), Toast.LENGTH_LONG).show();
			}
		}
	}
	
	public void onTakeNewPhotoClick(View v) {
		// the camera intent.
		Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		
		// where we wish to save the picture that the camera will take.
		File imageLocation = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "camerapic.jpg");
		
		// parse that to a URI.
		Uri pictureUri = Uri.fromFile(imageLocation);
		
		// associate this uri with the camera implicit intent.
		cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, pictureUri);
		
		// invoke camera.
		startActivityForResult(cameraIntent, CAMERA_REQUEST);
	}


}




